package com.entrogy.controller;

import com.Sinewecology.EntropyWechat.SignUtil;
import com.entrogy.service.impl.WeixinCoreServiceImpl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xlr
 *
 * @description 核心请求处理类
 *
 */
@SuppressWarnings("serial")
@RestController
@RequestMapping(value = "weixincore")
public class WeixinCoreController{

	/**
	 * 确认请求来自微信服务器
	 */
	@RequestMapping(value = "/weixindoget",method = RequestMethod.GET)
	public String weixinDoGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败

		if (signature != null)
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				return echostr;
			}
		return null;
	}

	/**
	 * 处理微信服务器发来的消息
	 */
	@RequestMapping(value = "weixindoget",method = RequestMethod.POST)
	private String weixinDoPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO 消息的接收、处理、响应
		// 消息的接收、处理、响应
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 调用核心业务类接收消息、处理消息
		String respXml = WeixinCoreServiceImpl.processRequest(request);

		// 响应消息
		return respXml;
	}

}
